package com.usermanage.controller;

import com.usermanage.SecurityConfig.SpringSecurityUtils;
import com.usermanage.Service.MessageService;
import com.usermanage.Service.UserCenterService;
import com.usermanage.Service.UserService;
import com.usermanage.beanParam.MessageBean;
import com.usermanage.beanParam.UserBean;
import com.usermanage.beanParam.UserCenterBean;
import com.usermanage.util.ErrMessageUtil;
import com.usermanage.util.JsonData;
import com.usermanage.util.StaticUtil;
import com.usermanage.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("userCenter")
public class UserCenterController {

    @Resource
    private UserService userService;
    @Resource
    private UserCenterService userCenterService;

    //账号信息页面
    @RequestMapping("/account/index.page")
    public ModelAndView indexPage() {
        ModelAndView mv = new ModelAndView();
        Optional<UserBean> optional = userService.findById(Integer.valueOf(SpringSecurityUtils.getCurrentUser().getId()));
        UserBean bean = optional.get();
        mv.addObject("bean", bean);
        Optional<UserCenterBean> optional1 = userCenterService.findById(Integer.valueOf(SpringSecurityUtils.getCurrentUser().getId()));
        UserCenterBean userCenterBean = optional1.get();
        mv.addObject("userCenterBean",userCenterBean);
        mv.addObject("url", StaticUtil.ORDERIP);
        mv.setViewName("/user/personal");
        return mv;
    }

    //账号信息更新提交
    @RequestMapping(value = "/account/update.json", method = RequestMethod.POST)
    @Transactional
    public JsonData updateUser(@Valid UserCenterBean userCenterBean, BindingResult bindingResult) {
        try {
            //验证提交数据是否合法
            if (bindingResult.hasErrors()) {
                return JsonData.fail(bindingResult.getFieldError().getDefaultMessage());
            }
            //根据id获取用户详情
            Optional<UserBean> optional = userService.findById(Integer.valueOf(userCenterBean.getId()));
            UserBean bean = optional.get();
            bean.setUser_name(userCenterBean.getUser_name());
            bean.setUser_phone(userCenterBean.getUser_phone());
            bean.setUser_dept(userCenterBean.getUser_dept());
            //修改用户的基本信息
            userService.save(bean);
            userCenterBean.setUser_id(Integer.valueOf(userCenterBean.getId()));
            userCenterService.save(userCenterBean);
            return JsonData.success();
        } catch (Exception e) {
            /**
             * 打印日志
             */
            return JsonData.fail(ErrMessageUtil.SysErr);
        }
    }

    //密码修改页面
    @RequestMapping("/psdUpdate/index.page")
    public ModelAndView psdUpdatePage() {
        ModelAndView mv = new ModelAndView();
        Optional<UserBean> optional = userService.findById(Integer.valueOf(SpringSecurityUtils.getCurrentUser().getId()));
        UserBean bean = optional.get();
        mv.addObject("bean", bean);
        mv.setViewName("/user/psdUpdate");
        return mv;
    }

    //旧密码验证
    @RequestMapping("/psdUpdate/checkOldPsd.json")
    public JsonData oldPsdUpdate(String id,String oldPsd) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        if(StringUtils.isNotBlank(oldPsd)&&StringUtils.isNotBlank(id)){
            Optional<UserBean> optional = userService.findById(Integer.valueOf(id));
            UserBean bean = optional.get();
            String psd = "{noop}" + StringUtil.EncoderByMd5(oldPsd);
            if(psd.equals(bean.getUser_password())){
                return JsonData.success("密码验证成功");
            }else{
                return JsonData.fail("密码验证错误");
            }
        }else{
            return JsonData.fail("请输入原密码");
        }
    }

    //密码修改提交
    @RequestMapping(value = "/psdUpdate/update.json",method = RequestMethod.POST)
    public JsonData psdUpdate(String id,String checkPass) throws Exception {
        if(StringUtils.isNotBlank(checkPass)&&StringUtils.isNotBlank(id)) {
            Optional<UserBean> optional = userService.findById(Integer.valueOf(id));
            UserBean bean = optional.get();
            String psd = "{noop}" + StringUtil.EncoderByMd5(checkPass);
            bean.setUser_password(psd);
            userService.save(bean);
            return JsonData.success();
        }else{
            return JsonData.fail("请输入密码");
        }
    }

//    @Autowired
//    private MessageService messageService;
//
//    @RequestMapping(value = "/test.json")
//    public void test(MessageBean messageBean) throws Exception {
//        log.info("----------"+StringUtil.ObjectToJson(messageBean));
//        messageService.dingSend(messageBean);
//    }

}
